package com.bwie.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.user.dao.GoodsDao;
import com.bwie.user.entity.GoodsEntity;
import com.bwie.user.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<>();
        //获取模糊查的key
        String key = (String) params.get("key");
        //页数
        String page1 = (String) params.get("page");
        if (StringUtils.isNotEmpty(key)){
            wrapper.like("goods_name",key);
        }
        //获取redis中信息
        IPage<GoodsEntity> goodsList =(IPage<GoodsEntity>) redisTemplate.boundHashOps("GoodsList").get("list");
        //先判断 redis中没有goods的信息， 并且key为null 就去数据库查找并存入
        if (goodsList==null&&Integer.parseInt(page1)==1&&StringUtils.isEmpty(key)){
            IPage<GoodsEntity> page = this.page(
                    new Query<GoodsEntity>().getPage(params),
                    wrapper
            );
            //存redis
            System.out.println("去查找并存入");
            redisTemplate.boundHashOps("GoodsList").put("list",page);
            //加入一个过期时间
            redisTemplate.expire("GoodsList",5, TimeUnit.MINUTES);
            return new PageUtils(page);
        }
        //redis中查到了数据，并页数是1,没有key，就去缓存查找
        else if(goodsList!=null&&Integer.parseInt(page1)==1&&StringUtils.isEmpty(key)){

            System.out.println("缓存命中");
            return new PageUtils(goodsList);
        }else {
            System.out.println("直接数据库查");
            IPage<GoodsEntity> page = this.page(
                    new Query<GoodsEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }
    }

    @Override
    public R goodsList() {
        ArrayList<GoodsEntity> list=goodsDao.goodsList();
        return R.ok().put("goods",list);
    }

}